const express = require('express');
const sqlQuery = require('./sql.js');
// 使用模板来渲染页面
const ejs = require('ejs');

const app = express();

// 模板引擎关联express
app.set('views' , 'views'); // 设置视图对应的目录
app.set('view engine', 'ejs'); //设置默认的模板引擎
app.set('ejs' , ejs._express);

app.get('/' , async (req , res)=>{
    // 数据库查询语句
    let strSql = 'select id,bookname,author,bookimg,viewcount from jianjie limit 0,5';
    let results = await sqlQuery(strSql);
    console.log(results);
    // res.send('这是首页');
    // res.json(Array.from(results));
    res.render('index.ejs', {title:'测试'});


})
app.get('/xiaoshuowenxue' , async (req , res)=>{
    // 数据库查询语句
    let strSql = 'select id,bookname,author,bookimg,viewcount from jianjie where viewcount="小说文" limit 0,5';
    let results = await sqlQuery(strSql);
    console.log(results);
    res.json(Array.from(results));
    // res.send('这是分类页');
})

// 动态路由
app.get('/books/:bookid' , async (req , res)=>{
    // 数据库查询语句
    let strSql = 'select * from jianjie where id=?';
    // 拿到页面的url中的动态路由
    let bookid = req.params.bookid;
    let results = await sqlQuery(strSql , [bookid]);
    console.log(results);
    res.json(Array.from(results));
    // res.send('这是书籍详情页');
})

module.exports = app;